package com.jushu.storbox.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;

import com.jushu.storbox.util.LogUtil;

/***
 * 
 * Common Dialog
 */
public abstract class AbsPopupMenuDialog extends Dialog {
	private final static String LOG_TAG = "ClouddriveDialog";
	private int resourceId;
	private Context context;
	private int width = LayoutParams.WRAP_CONTENT;
	private int heigth = LayoutParams.WRAP_CONTENT;
	private View conventView;
	private boolean oncancleOutside = false;

	public AbsPopupMenuDialog(Context context, int theme, int resourceId) {
		super(context, theme);
		LogUtil.i(LOG_TAG, "ClouddriveDialog");
		this.resourceId = resourceId;
		this.context = context;
	}

	public AbsPopupMenuDialog(Context context, int resourceId) {
		super(context);
		LogUtil.i(LOG_TAG, "ClouddriveDialog");
		this.resourceId = resourceId;
		this.context = context;
	}

	public void setWindowWidth(int width) {
		this.width = width;
	}
	
	public void setWindowHeigth(int heigth) {
		this.heigth = heigth;
	}
	
	public void setGravity(int gravity) {
		getWindow().setGravity(gravity);
	}
	
	public void setPosition(int offsetX, int offsetY) {
		WindowManager.LayoutParams attr = getWindow().getAttributes();
		attr.x = offsetX;
		attr.y = offsetY;
		getWindow().setAttributes(attr);
	}
	
	/**
	 * 	gravity => Gravity.LEFT;Gravity.RIGHT;Gravity.TOP;Gravity.BOTTOM;Gravity.LEFT | Gravity.TOP...;</br>
	 * when gravity have Gravity.LEFT then x is offset to left,else have Gravity.RIGHT then x is offset to right</br>
	 * y is same as x</br>
	 */
	public void setWindowPosition(int gravity, int offsetX, int offsetY) {
		setGravity(gravity);
		setPosition(offsetX, offsetY);
	}

	@Override
	public void show() {
		if (null == conventView) {
			conventView = LayoutInflater.from(context).inflate(resourceId, null);
			onInflaterFinished(conventView);
			LayoutParams params = new LayoutParams(width, heigth);
			setContentView(conventView, params);
		}
		super.show();
	}

	@Override
	public void setCanceledOnTouchOutside(boolean cancel) {
		this.oncancleOutside = cancel;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (MotionEvent.ACTION_DOWN == event.getAction() && oncancleOutside) {
			dismiss();
		}
		return super.onTouchEvent(event);
	}
	
	public abstract void onInflaterFinished(View contentView);
}
